package com.wlstock.funi.request;

import java.util.List;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.utils.StockUtils;

/**
 * 
 * @author admin
 *	获取股票新浪实时行情
 */
public class SinaPriceRequest implements Listener<String>,ErrorListener {
	
	private static final int REPEAT_TIMES = 0;
	private static final int TIME_OUT = 5000;
	
	public  NetWorkListener    listener;
	private EventBusConstants  eventCode;
	private String 			   eventCodeStr;
	
	public SinaPriceRequest(){
		super();
	}
	
	public SinaPriceRequest(EventBusConstants eventCode){
		super();
		this.eventCode = eventCode;
	}
	
	public SinaPriceRequest(String eventCodeStr) {
		super();
		this.eventCodeStr = eventCodeStr;
	}

	public void request(List<String> stockList,final EventBusConstants eventCode) {
		this.eventCode = eventCode;
		StringRequest request = new StringRequest(Method.GET, getUrl(stockList), this, this);
		request.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT, REPEAT_TIMES, 1));
		RequestQueue mRequestQueue = FundApplication.getInstance().getRequestQueue();
		mRequestQueue.add(request);
		mRequestQueue.start();
	}
	
	public void request(String stkNO,final EventBusConstants eventCode) {
		this.eventCode = eventCode;
		String prefix = StockUtils.parsetStkCode2ZB(stkNO);
		String url  = "http://hq.sinajs.cn/list=" + prefix + stkNO;
		StringRequest request = new StringRequest(Method.GET, url, this, this);
		request.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT, REPEAT_TIMES, 1));
		RequestQueue mRequestQueue = FundApplication.getInstance().getRequestQueue();
		mRequestQueue.add(request);
		mRequestQueue.start();
	}
	
	private static String getUrl(List<String> params) {
		int size = params.size();
		StringBuffer stkListSB = new StringBuffer();
		for (int i = 0; i < size; i++) {
			String prefix = StockUtils.parsetStkCode2ZB(params.get(i));
			stkListSB.append(prefix).append(params.get(i)).append(",");
		}
		return "http://hq.sinajs.cn/list="+stkListSB.toString();
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		// TODO Auto-generated method stub
		if (eventCodeStr!=null && listener!=null) {
			listener.onErrorResponse(error, eventCodeStr);
		} else if (eventCode!=null && listener!=null) {
			listener.onErrorResponse(error, eventCode);
		}
	}

	@Override
	public void onResponse(String response) {
		// TODO Auto-generated method stub
		if (eventCodeStr!=null && listener!=null) {
			listener.onResponse(response, eventCodeStr);
		} else if (eventCode!=null && listener!=null) {
			listener.onResponse(response, eventCode);
		}
	}
}
